package com.foodapp.back.interceptor;

import com.alibaba.fastjson.JSON;
import com.foodapp.back.common.Result;
import com.foodapp.back.common.ResultCode;
import com.foodapp.back.util.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("Authorization");
        
        // 判断token是否存在
        if (StringUtils.isBlank(token)) {
            // 返回未认证
            returnJson(response, Result.error(ResultCode.UNAUTHORIZED));
            return false;
        }
        
        // 验证token是否有效
        boolean isValid = jwtTokenUtil.validateToken(token);
        if (!isValid) {
            // 返回未认证
            returnJson(response, Result.error(ResultCode.UNAUTHORIZED));
            return false;
        }
        
        // 如果是管理员接口，需要验证是否有管理员权限
        if (request.getRequestURI().startsWith("/admin")) {
            String role = jwtTokenUtil.getRoleFromToken(token);
            if (!"admin".equals(role)) {
                // 返回未授权
                returnJson(response, Result.error(ResultCode.FORBIDDEN));
                return false;
            }
        }
        
        // 将用户ID和角色存入请求属性中，方便后续使用
        request.setAttribute("userId", jwtTokenUtil.getUserIdFromToken(token));
        request.setAttribute("username", jwtTokenUtil.getUsernameFromToken(token));
        request.setAttribute("role", jwtTokenUtil.getRoleFromToken(token));
        
        return true;
    }

    /**
     * 返回JSON数据
     */
    private void returnJson(HttpServletResponse response, Object result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSON.toJSONString(result));
            writer.flush();
        }
    }
}
